import socket
import struct
import threading
import time
from datetime import datetime


def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])


server_port = 60000
float_to_hex(17.5)  # Output: '0x418c0000'


# 49152-65535
class ThreadedServer():
    def __init__(self):
        # self.host = socket.gethostname()
        self.host = '192.168.4.200'
        self.port = server_port
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        print(self.host)
        self.s.bind((self.host, self.port))
        self.running = True

    def listen(self):
        self.s.listen(5)
        while True:
            c, addr = self.s.accept()
            c.settimeout(100)  # 当socket尝试重连到60秒时，就会停止一切操作
            threading.Thread(target=self.listenToClient, args=(c, addr)).start()  # args 传递参数

    def listenToClient(self, c, addr):
        block_size = 1024
        print('Got connection from', addr)

        radar_steart = c.recv(12)  # 接收系统信号
        print(radar_steart)

        if (radar_steart == b'\xa5\x5a\x10\xb5\x03\x01\x00\x00\x00\xa0\x69'):
            radar_steart_respond = b'\xA5\x5A\xB5\x10\xA2\x02\x00\x00\x00\x03\x0F\x7B'
            c.send(radar_steart_respond)

            c.send(b'start')
            time.sleep(0.500)

            c.send(b'1')
            radar_time0 = str(datetime.now())
            time.sleep(0.500)
            c.send(radar_time0.encode("utf-8"))

            sys = c.recv(1)  # 接收系统信号
            radar_time1 = str(datetime.now())
            print("收到报文：", sys)
            c.send(radar_time1.encode("utf-8"))
            print(radar_time0)
            print(radar_time1)

            c.close()


if __name__ == "__main__":
    ThreadedServer().listen()
